const uuid = require('uuid')

function thirdPartyUserId() {
  // 生成随机的uuid, 如果想根据timestamp生成可以调用v1
  // https://github.com/uuidjs/uuid
  return uuid.v4()
}

function messageId() {
  // 生成随机的uuid, 如果想根据timestamp生成可以调用v1
  // https://github.com/uuidjs/uuid
  return uuid.v4()
}

function granteeId() {
  // 生成随机的uuid, 如果想根据timestamp生成可以调用v1
  // https://github.com/uuidjs/uuid
  return uuid.v4()
}

function thirdPartyDevId(thirdPartyId) {
  return `${thirdPartyId}${random(23, { specials: false })}` // 32位
}

function vin(tag) {
  return `${tag}${random(14, { specials: false })}` // 17位
}

/**
 * 随机函数封装
 * @param length
 * @param options
 * @returns {string}
 */
function random(length, options) {
  const numbers = '0123456789'
  const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  const specials = '~!@#$%^*()_+-=[]{}|;:,./<>?'

  length || (length = 8)
  options || (options = {})

  var chars = ''
  var result = ''

  if (options === true) {
    chars = numbers + letters + specials
  } else if (typeof options === 'string') {
    chars = options
  } else {
    if (options.numbers !== false) {
      chars += (typeof options.numbers === 'string') ? options.numbers : numbers
    }

    if (options.letters !== false) {
      chars += (typeof options.letters === 'string') ? options.letters : letters
    }

    if (options.specials) {
      chars += (typeof options.specials === 'string') ? options.specials : specials
    }
  }

  while (length > 0) {
    length--
    result += chars[Math.floor(Math.random() * chars.length)]
  }
  return result
}

module.exports = {
  thirdPartyUserId,
  thirdPartyDevId,
  granteeId,
  vin,
  messageId
}
